<template>
  <el-card class="box-card" shadow="never">
    <div class="w-full mx-auto">
      <!-- {{ formData }}
      <hr />
      {{ formData.fields_json }} -->
      <el-form :model="formData" ref="form" label-width="100px">
        <el-form-item
          style="position: relative"
          label="视图名称"
          prop="table_name"
          :rules="[
            {
              required: true,
              message: '视图名称不能为空',
            },
          ]"
        >
          <el-input v-model="formData.table_name" clearable placeholder="输入对视图名称匹配对应字段名称" width="200" @keydown.enter="controllerBlur" />
          <el-button type="default" @click="controllerBlur" style="width: 60px; position: absolute; top: 0; right: -70px; font-weight: bold">匹配</el-button>
        </el-form-item>
        <el-form-item
          label="报表名称"
          prop="report_name"
          :rules="[
            {
              required: true,
              message: '报表名称不能为空',
            },
          ]"
        >
          <el-input v-model="formData.report_name" clearable placeholder="请输入自定义报表名称" width="200" />
        </el-form-item>

        <el-table :data="formData.fields_json" border v-loading="selfLoading">
          <!-- <el-table-column prop="column" label="字段名称" width="180">
            <template #default="scope">
              <el-form-item :prop="'fields_json.' + scope.$index + '.column'">
                <el-input v-model="scope.row.column" name="column" clearable />
              </el-form-item>
            </template>
          </el-table-column> -->

          <el-table-column prop="column" label="字段名称" width="150px" />
          <el-table-column prop="label" label="表头名称" width="200px">
            <template #default="scope">
              <el-input v-model="scope.row.label" />
            </template>
          </el-table-column>

          <el-table-column prop="is_show" label="显示">
            <template #default="scope">
              <el-switch v-model="scope.row.is_show" inline-prompt :active-text="$t('system.yes')" :inactive-text="$t('system.no')" width="45px" />
            </template>
          </el-table-column>

          <el-table-column prop="is_query" label="查询">
            <template #default="scope">
              <el-switch v-model="scope.row.is_query" inline-prompt :active-text="$t('system.yes')" :inactive-text="$t('system.no')" width="45px" />
            </template>
          </el-table-column>

          <el-table-column prop="query_compont" label="查询组件" width="200px">
            <template #default="scope">
              <el-select v-model="scope.row.query_compont" class="w-full" filterable>
                <el-option v-for="component in formComponents" :key="component" :label="component" :value="component" />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column prop="condition" label="查询操作符" width="200px">
            <template #default="scope">
              <el-select v-model="scope.row.condition" class="w-full">
                <el-option v-for="op in operates" :key="op" :label="op" :value="op" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <div class="w-full flex justify-center pt-5">
      <!-- <el-button type="primary" @click="submitformDataerate(form)">{{ $t('system.confirm') }}</el-button> -->
      <el-button type="primary" @click="submitformDataerate(form)">保存</el-button>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { useCreate } from '/admin/composables/curd/useCreate'
import { useShow } from '/admin/composables/curd/useShow'
import { useGenerateStore } from './store'
import { onMounted, reactive, ref, watch, defineProps } from 'vue'
import http from '/admin/support/http'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['close'])

const props = defineProps({
  primary: String | Number,
  api: String,
})

const { formData, loading, submitForm, close } = useCreate(props.api, props.primary)

if (props.primary) {
  useShow(props.api, props.primary, formData)
  // formData.value.fields_json = JSON.parse(formData.value.fields_json)
  console.log(formData)
}

const selfLoading = ref(false)

const controllerBlur = e => {
  selfLoading.value = true
  // console.log('控制器拿到的数据', formData.value.table_name)
  http.get(`customReport/show/table/${formData.value.table_name}`).then(r => {
    // console.log('获取column', r.data)
    selfLoading.value = false
    if (r.data.code == 10000) {
      ElMessage.success(r.data.message)
      let getcolumns = r.data.data.column

      // console.log('请求匹配的箱号', getcolumns)
      // console.log('原数组', formData.value.fields_json)
      let reColumns = []
      if (formData.value.fields_json) {
        reColumns = formData.value.fields_json.reduce((prev, item) => {
          prev.push(item.column)
          return prev
        }, [])
      }

      // console.log('原字段', reColumns)

      // 新匹配的箱号若有原数组字段，保留
      // 若无，删除
      // 若有原数组没有的，赋予默认值

      formData.value.fields_json = getcolumns.map(item => {
        console.log(reColumns.includes(item))
        if (reColumns.includes(item)) {
          // console.log('请求字段有相同', item)
          return formData.value.fields_json.find(ele => ele.column == item)
        } else {
          return {
            column: item,
            label: item,
            is_show: true,
            is_query: false,
            query_compont: '',
            condition: '',
          }
        }
      })

    }
  })
}

const form = ref<FormInstance>()
const submitformDataerate = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      // console.log('提交表格', formData.value)
      let flag = true
      try {
        formData.value.fields_json.forEach(item => {
          let str = ''
          if (item.is_query) {
            if (item.is_query == '' || item.is_query == undefined) {
              flag = false
              // str = '若需要查询，查询组件必选哦！'
              throw new Error(str)
            }
            if (item.condition == '' || item.condition == undefined) {
              flag = false
              // str = '若需要查询，查询操作符必填哦！'
              throw new Error(str)
            }
           
          }
        })
      } catch (e) {
        console.log(e);
        ElMessage.warning('若需要查询，查询组件和查询操作符必填哦！')
      }

      if (flag) {
        let sendObj = {
          table_name: formData.value.table_name,
          report_name: formData.value.report_name,
          fields_json: formData.value.fields_json,
        }
        console.log('生成的提交数据', sendObj)

        if (props.primary) {
          // 修改
          http.put(`customReport/manage/${props.primary}`, sendObj).then(r => {
            ElMessage.success(r.data.message)
            emit('close')
          })
        } else {
          // 新增
          http.post('customReport/manage', sendObj).then(r => {
            ElMessage.success(r.data.message)
            emit('close')
          })
        }
      }
    } else {
      return false
    }
  })
}

const operates: string[] = ['=', '!=', '>', '>=', '<', '<=', 'like']

const validates: string[] = [
  'required',
  'integer',
  'numeric',
  'string',
  'timezone',
  'url',
  'uuid',
  'date',
  'alpha',
  'alpha_dash',
  'alpha_num',
  'boolean',
  'email',
  'image',
  'file',
  'ip',
  'ipv4',
  'ipv6',
  'mac_address',
  'json',
  'nullable',
  'present',
  'prohibited',
]
// const formComponents: string[] = ['cascader', 'date', 'datetime', 'input', 'input-number', 'radio', 'rate', 'select', 'tree', 'tree-select']
const formComponents: string[] = ['input']
</script>

<style lang="css">
.el-form-item {
  width: 450px;
}
</style>
